import numpy as np
import dlib
import cv2
import xml_functions as rx

def shape_to_np(shape, dtype="int"):
	# 创建68*2
	coords = np.zeros((shape.num_parts, 2), dtype=dtype)
	# 遍历每一个关键点
	# 得到坐标
	for i in range(0, shape.num_parts):
		coords[i] = (shape.part(i).x, shape.part(i).y)  # 第i个关键点的横纵坐标。
	return coords

def getEasyBox(frame):
    padding = int(frame.shape[1]/10.8)
    box = dlib.rectangle(padding,padding,frame.shape[1]-padding, frame.shape[0]-padding)
    return box

MP4NAME = 'VID_20211206_170004'

def setMp4Name(name):
    """设置视频名字"""
    MP4NAME = name

def openMp4():
    """打开视频"""
    #获得视频的格式
    videoCapture = cv2.VideoCapture('./projects/video/'+MP4NAME+'.mp4')
 
    #获得码率及尺寸
    fps = videoCapture.get(cv2.CAP_PROP_FPS)#获取实时帧率
    size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    fNUMS = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)#获取总帧数
    
    success, frame = readNewFrame(videoCapture)
    return videoCapture,fps,size,fNUMS,success, frame

def closeMp4(video):
    """关闭视频"""
    video.release()
    
def showMp4(frame,fps):
    """显示一帧的图像"""
    cv2.imshow('windows', frame) #显示
    cv2.waitKey(int(1000/int(fps))) #延迟

def readNewFrame(video):
    """读取下一帧"""
    success, frame = video.read()
    return success, frame

def startRecording():
    # 加载人脸检测与关键点定位
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('data/shape_predictor_68_face_landmarks.dat')
    # 加载视频
    videoCapture,fps,size,fNUMS,success, frame = openMp4()
    #图片缩放尺寸
    (h, w) = frame.shape[:2]
    width=354
    r = width / float(w)
    dim = (width, int(h * r))
    a = 0
    while success :
        # 读取输入数据，预处理
        frame = cv2.resize(frame, dim, interpolation=cv2.INTER_NEAREST)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 人脸检测
        rects = detector(gray, 1)
        # 遍历检测到的框
        for (_, rect) in enumerate(rects):
            # 对人脸框进行关键点定位
            # 转换成ndarray
            print(rect)
            shape = predictor(gray, rect)
            shape = shape_to_np(shape)
            print(a)
            # 根据位置画点
            for (x, y) in shape:
                cv2.circle(frame, (x, y), 3, (0, 0, 255), -1)
            showMp4(frame,fps)
            images_path = 'images/' + MP4NAME + '_frame' + str(a) + '.jpg'
            cv2.imwrite('projects/' + images_path, frame)
            rect = getEasyBox(frame)
            print(rect)
            print("----------")
            rx.appendXML(shape,rect,images_path,'projects/New0_source.xml')
        a = a + 1
        for i in range(30):#跳帧取图
            success, frame = readNewFrame(videoCapture) #获取下一帧


    closeMp4(videoCapture)